package com.adcc.loadsheet.billing.service.impl;

import com.adcc.aoc.devLib.common.log.Log;
import com.adcc.loadsheet.billing.entity.ScUpDataEntity;
import com.adcc.loadsheet.billing.entity.chargerule.BillingLadderEntity;
import com.adcc.loadsheet.billing.entity.contractuser.ContractUserEntity;
import com.adcc.loadsheet.billing.entity.export.BaseItem;
import com.adcc.loadsheet.billing.entity.export.Billing;
import com.adcc.loadsheet.billing.entity.export.TwoItem;
import com.adcc.loadsheet.billing.service.ChargeBillService;
import com.adcc.loadsheet.billing.service.ChargeDetailService;
import com.adcc.loadsheet.billing.util.ExcelUtil;
import com.adcc.loadsheet.billing.util.FileUtil;
import com.adcc.loadsheet.billing.util.PrintUtil;
import com.adcc.loadsheet.billing.vo.ScUpDataEntityVO;
import com.adcc.loadsheet.billing.vo.chargebill.ChargeBillVO;
import com.adcc.loadsheet.billing.vo.chargedetail.ChargeDetailVO;
import com.deepoove.poi.XWPFTemplate;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * 收费明细Service实现类
 * Created by zhaoml on 2020/5/7.
 */
@Service
public class ChargeDetailServiceImpl extends BasisServiceImpl implements ChargeDetailService {

    @Autowired
    ChargeBillService chargeBillService;

    //查询收费明细
    @Override
    public List<ChargeDetailVO> getChargeDetails(String startDate, String endDate, Integer contractUserId){
//        List<ChargeDetailVO> chargeDetailVOS = Lists.newArrayList();
//        //获取两个日期之间的所有日期集合（正序排列）
//        List<String> dates = DateTimeUtil.getBetweenDates(startDate,endDate);
//        ChargeDetailVO chargeDetailVO = null;
//        for(String date : dates){
//            //计费明细（舱单数据服务航班数、旅客名单服务航班数、当月重发航班数）（结束日期往后取一天）
//            chargeDetailVO = scUpDataEntityMapper.getChargeDetailNum(date,date,contractUserId);
//            chargeDetailVO.setDate(date);
//            chargeDetailVOS.add(chargeDetailVO);
//        }
        List<ChargeDetailVO> chargeDetailVOS =scUpDataEntityMapper.getALLChargeDetailNum(startDate,endDate,contractUserId);
        return chargeDetailVOS;
    }

    //下载word格式
    @Override
    public String word(String startDate,String endDate,Integer contractUserId,HttpServletResponse response) throws Exception{
        //填充模板内容，通过合同用户查计费阶梯
        mode(startDate,endDate,contractUserId);

        String result = "OK";
        try{
            response.setHeader("content-type", "application/octet-stream");
            response.setContentType("application/octet-stream");
            // 下载文件能正常显示中文
            ContractUserEntity contractUserEntity = contractUserEntityMapper.selectByPrimaryKey(contractUserId);
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(contractUserEntity.getUserAbbrev() + "收费明细.docx", "UTF-8"));
            // 实现文件下载
            OutputStream out = response.getOutputStream();
            byte[] buffer = new byte[1024];
//            String path = ClassUtils.getDefaultClassLoader().getResource("").getPath();
            FileInputStream fis = new FileInputStream("output.docx");
            BufferedInputStream bis = new BufferedInputStream(fis);
            int i = bis.read(buffer);
            while (i != -1) {
                out.write(buffer, 0, i);
                i = bis.read(buffer);
            }
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            out.flush();
            out.close();
        }catch (Exception ex){
            result = ex.getMessage();
        }
        return result;
    }

    //下载pdf格式
    @Override
    public String pdf(String startDate,String endDate,Integer contractUserId,HttpServletResponse response) throws Exception{
        //填充模板内容
         mode(startDate,endDate,contractUserId);

        String result = "OK";
//        String path = ClassUtils.getDefaultClassLoader().getResource("").getPath();
        //word转pdf
        try  {

//            InputStream docxInputStream = new FileInputStream("output.docx");
//            OutputStream outputStream = new FileOutputStream("output.pdf");
//            IConverter converter = LocalConverter.builder().build();
//            converter.convert(docxInputStream).as(DocumentType.DOCX).to(outputStream).as(DocumentType.PDF).execute();
//            outputStream.close();
//            File inputFile=new File("output.docx");
//            File outputFile=new File("output.pdf");
//            converter.convert(inputFile).to(outputFile).execute();
            System.out.println("success");
        } catch (Exception e) {
            Log.error(ChargeDetailServiceImpl.class,"转换pdf出错",e);
            return e.getMessage();
        }
        //pdf下载
        try{
            response.setHeader("content-type", "application/octet-stream");
            response.setContentType("application/octet-stream");
            // 下载文件能正常显示中文
            ContractUserEntity contractUserEntity = contractUserEntityMapper.selectByPrimaryKey(contractUserId);
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(contractUserEntity.getUserAbbrev() + "收费明细.pdf", "UTF-8"));
            // 实现文件下载
            OutputStream out = response.getOutputStream();
            byte[] buffer = new byte[1024];

            FileInputStream fis = new FileInputStream("output.pdf");
            BufferedInputStream bis = new BufferedInputStream(fis);
            int i = bis.read(buffer);
            while (i != -1) {
                out.write(buffer, 0, i);
                i = bis.read(buffer);
            }
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            out.flush();
            out.close();
        }catch (Exception ex){
            result=ex.getMessage();
        }
        return result;
    }

    //填充模板内容
    private Billing mode(String startDate,String endDate,Integer contractUserId) throws Exception{
        String result = "OK";
        Billing bill = null;
        try{
            //通过合同用户查计费阶梯
            ContractUserEntity contractUserEntity = contractUserEntityMapper.selectByPrimaryKey(contractUserId);
            List<BillingLadderEntity> billingLadderEntityList = billingLadderEntityMapper.selectByBillingRuleId(contractUserEntity.getBillingRuleId());

            //查询收费账单
            ChargeBillVO chargeBillVO = chargeBillService.getChargeBill(startDate,endDate,contractUserEntity,billingLadderEntityList);
            bill = new Billing(chargeBillVO);

            //如果查询的合同用户为机场用户则此处显示“航司名称”，按照航司名称进行分组显示；
            //如果查询的合同用户为航司用户则此处显示“起飞机场”，按照起飞机场进行分组显示。
            List<TwoItem> detail = new LinkedList<>();
            if(contractUserEntity.getUserType().equals(1)){
                bill.setType("航司名称");
                detail = statisticalAirline(startDate, endDate,contractUserId);
            }else if(contractUserEntity.getUserType().equals(2)){
                bill.setType("起飞机场");
                detail = statisticalAirport(startDate, endDate,contractUserId);
            }
            bill.setDetail(detail);

            //页面内容
            List<TwoItem> month = statisticalChargeDetails(startDate,endDate,contractUserId);
            bill.setMonth(month);

            //相对路径获取
//            String path = ClassUtils.getDefaultClassLoader().getResource("").getPath();
            //detail.docx模板名称
            XWPFTemplate template = XWPFTemplate.compile("detail.docx").render(bill);
            //output.docx数据填充后账单文件
            FileOutputStream out = new FileOutputStream("output.docx");
            template.write(out);
            out.flush();
            out.close();
            template.close();
        }catch (Exception ex){
            throw ex;
        }
        return bill;
    }

    //统计机场
    private List<TwoItem> statisticalAirport(String startDate,String endDate,Integer contractUserId){
        List<TwoItem> detail = new LinkedList<>();
        //统计机场
        List<ScUpDataEntity> scUpDataEntityList = scUpDataEntityMapper.statisticalAirport(startDate,endDate,contractUserId);
        for(int i = 0;i <= scUpDataEntityList.size()-1;i = i+2){
            TwoItem two2 = new TwoItem();
            BaseItem one1 = new BaseItem();
            ScUpDataEntity scUpDataEntity = scUpDataEntityList.get(i);
            String name1=scUpDataEntity.getTko();
            if(!Strings.isNullOrEmpty(scUpDataEntity.getAirportname())){
                name1=name1+"/"+scUpDataEntity.getAirportname();
            }
            one1.setName(name1);
            one1.setLoadsheet(scUpDataEntity.getLoadsheetnum().toString());
            one1.setPassgerlist(scUpDataEntity.getPassgerlistnum().toString());
            two2.setItem1(one1);

            if(scUpDataEntityList.size() > i+1){
                BaseItem one2 = new BaseItem();
                ScUpDataEntity scUpDataEntity2 = scUpDataEntityList.get(i+1);
                String name2=scUpDataEntity2.getTko();
                if(!Strings.isNullOrEmpty(scUpDataEntity2.getAirportname())){
                    name2=name2+"/"+scUpDataEntity2.getAirportname();
                }
                one2.setName(name2);
                one2.setLoadsheet(scUpDataEntity2.getLoadsheetnum().toString());
                one2.setPassgerlist(scUpDataEntity2.getPassgerlistnum().toString());
                two2.setItem2(one2);
            }
            detail.add(two2);
        }
        return detail;
    }

    //统计航司
    private List<TwoItem> statisticalAirline(String startDate,String endDate,Integer contractUserId){
        List<TwoItem> detail = new LinkedList<>();
        //统计航司
        List<ScUpDataEntity> scUpDataEntityList = scUpDataEntityMapper.statisticalAirline(startDate,endDate,contractUserId);
        for(int i = 0;i <= scUpDataEntityList.size()-1;i = i+2){
            TwoItem two2 = new TwoItem();
            BaseItem one1 = new BaseItem();
            ScUpDataEntity scUpDataEntity = scUpDataEntityList.get(i);
            String name1=scUpDataEntity.getAirline();
            if(!Strings.isNullOrEmpty(scUpDataEntity.getChsShortname())){
                name1=name1+"/"+scUpDataEntity.getChsShortname();
            }
            one1.setName(name1);
            one1.setLoadsheet(scUpDataEntity.getLoadsheetnum().toString());
            one1.setPassgerlist(scUpDataEntity.getPassgerlistnum().toString());
            two2.setItem1(one1);

            if(scUpDataEntityList.size() > i+1){
                BaseItem one2 = new BaseItem();
                ScUpDataEntity scUpDataEntity2 = scUpDataEntityList.get(i+1);
                String name2=scUpDataEntity2.getAirline();
                if(!Strings.isNullOrEmpty(scUpDataEntity2.getChsShortname())){
                    name2=name2+"/"+scUpDataEntity2.getChsShortname();
                }
                one2.setName(name2);
                one2.setLoadsheet(scUpDataEntity2.getLoadsheetnum().toString());
                one2.setPassgerlist(scUpDataEntity2.getPassgerlistnum().toString());
                two2.setItem2(one2);
            }
            detail.add(two2);
        }
        return detail;
    }

    //统计计费明细（导出用）
    private List<TwoItem> statisticalChargeDetails(String startDate, String endDate, Integer contractUserId){
        List<TwoItem> month = new LinkedList<>();
        List<ChargeDetailVO> chargeDetailVOS = getChargeDetails(startDate,endDate,contractUserId);
        for(int i = 0;i <= chargeDetailVOS.size()-1;i = i+2){
            ChargeDetailVO chargeDetailVO = chargeDetailVOS.get(i);
            TwoItem two = new TwoItem();
            BaseItem one = new BaseItem();
            one.setName(chargeDetailVO.getDate());
            one.setLoadsheet(chargeDetailVO.getLoadsheetNum().toString());
            one.setPassgerlist(chargeDetailVO.getPassgerListNum().toString());
            two.setItem1(one);

            if(chargeDetailVOS.size() > i+1){
                ChargeDetailVO chargeDetailVO2 = chargeDetailVOS.get(i+1);
                BaseItem one2 = new BaseItem();
                one2.setName(chargeDetailVO2.getDate());
                one2.setLoadsheet(chargeDetailVO2.getLoadsheetNum().toString());
                one2.setPassgerlist(chargeDetailVO2.getPassgerListNum().toString());
                two.setItem2(one2);
            }
            month.add(two);
        }
        return month;
    }

    //查询明细
    @Override
    public List<ScUpDataEntityVO> getDetails(String startDate, String endDate, Integer contractUserId){
        List<ScUpDataEntityVO> vos = Lists.newArrayList();
        List<ScUpDataEntity> details = scUpDataEntityMapper.details(startDate,endDate,contractUserId);
        details.stream().forEach(entity -> vos.add(entity.toVO()));
        return vos;
    }

    //导出明细excel
    @Override
    public void excel(String startDate,String endDate,Integer contractUserId,HttpServletResponse response){
        HSSFWorkbook hssfWorkbook = getHSSFWorkbook(startDate,endDate,contractUserId);

        ContractUserEntity contractUserEntity = contractUserEntityMapper.selectByPrimaryKey(contractUserId);
        ExcelUtil.returnClient(response, contractUserEntity.getUserAbbrev() + "账单明细表.xls", hssfWorkbook);
    }

    //填充明细Excel
    private HSSFWorkbook getHSSFWorkbook(String startDate,String endDate,Integer contractUserId){
        String[] titles = new String[]{"日期", "航空公司","类别", "航班号", "起落机场", "机尾号","发送时间","状态","回复","确认","发送人","重发"};
        Map<String, Object> paramMap = Maps.newConcurrentMap();

        List<ScUpDataEntityVO> details = getDetails(startDate,endDate,contractUserId);
        String[][] values = new String[details.size()][titles.length];
        if (details != null && details.size() > 0) {
            ScUpDataEntityVO vo;
            for (int i = 0; i < details.size(); i++) {
                vo = details.get(i);
                values[i][0] = vo.getCreateTimeStr();
                values[i][1] = vo.getChsShortname();
                values[i][2] = vo.getType();
                values[i][3] = vo.getFi();
                values[i][4] = vo.getTkoAndDesStr();
                values[i][5] = vo.getAn();
                values[i][6] = vo.getSendTimeStr();
                values[i][7] = vo.getStateStr();
                values[i][8] = vo.getLastAutoAckStateStr();
                values[i][9] = vo.getLastManuAckStateStr();
                values[i][10] = vo.getPB_NAME();
                values[i][11] = vo.getRepect();
            }
        }
        return ExcelUtil.getHSSFWorkbook("导出明细数据", titles, values);
    }

    //打印
    @Override
    public void print(String startDate,String endDate,Integer contractUserId,HttpServletResponse response) throws Exception{
        //填充模板内容
        mode(startDate,endDate,contractUserId);

//        String path = ClassUtils.getDefaultClassLoader().getResource("").getPath()+"/output.docx";
        File file=new File("output.docx");
        PrintUtil.printFile(file.getAbsolutePath(),1);
    }

    //打印明细excel
    @Override
    public void printDetails(String startDate,String endDate,Integer contractUserId,HttpServletResponse response){
        String fileName = "excelDetails.xls";
        try{
            HSSFWorkbook hssfWorkbook = getHSSFWorkbook(startDate,endDate,contractUserId);
            FileOutputStream output = new FileOutputStream(fileName);
            hssfWorkbook.write(output);
            output.flush();
        }catch (Exception ex){
            ex.printStackTrace();
        }
        File file = new File(fileName);
        PrintUtil.printFile(file.getAbsolutePath(),1);
    }

    //下载word格式
    @Override
    public String wordForTask(String startDate,String endDate,Integer contractUserId,String filePath){
        try{
            //填充模板内容，通过合同用户查计费阶梯
            Billing billing = mode(startDate, endDate, contractUserId);

            //转存到指定文件夹内
            File file = new File("output.docx");
            FileUtil.copyFile(file,new File(filePath));

            //删output.docx
            file.delete();
            return billing.getCost();
        }catch (Exception ex){
            ex.printStackTrace();
            return "";
        }
    }
}